package com.bree.erp.service.stateless;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.PurchaseOrder;
import com.bree.erp.entity.PurchaseRequisition;
import com.bree.erp.entity.Status;
import com.bree.erp.entity.Supplier;
import com.bree.erp.entity.User;
import com.bree.erp.service.PurchaseOrderService;

@Stateless
public class PurchaseOrderServiceBean implements PurchaseOrderService {

	@PersistenceContext()
	private EntityManager em;
	
	public PurchaseOrderServiceBean() {
		
	}
	
	public PurchaseOrderServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public PurchaseOrder create(Long prId, Long supplierId, String userId) {
		
		PurchaseOrder order = new PurchaseOrder();
		
		PurchaseRequisition pr = em.find(PurchaseRequisition.class,prId);
		Supplier supplier = em.find(Supplier.class, supplierId);
		User user = em.find(User.class, userId);
		
		order.setPurchaseRequisition(pr);
		order.setSupplier(supplier);
		order.setStatus(Status.OPEN);
		
		order.auditCreate(user);
		
		em.persist(order);
		
		return order;
	}

	@Override
	public PurchaseOrder read(Long id, boolean refresh) {
		
		PurchaseOrder entity =  em.find(PurchaseOrder.class, id);
		if(entity != null && refresh == true) {
			em.refresh(entity);
		}
		
		return entity;
	}

	@Override
	public PurchaseOrder read(Long id) {
		
		return read(id, false);
	}

	@Override
	public PurchaseOrder read(Long prId, Long supplierId, Status status) {
		
		PurchaseRequisition purchaseRequisition = em.find(PurchaseRequisition.class, prId);
		Supplier supplier = em.find(Supplier.class, supplierId);
		
		TypedQuery<PurchaseOrder> query = em.createNamedQuery(PurchaseOrder.QUERY_SELECT_PURCHASEORDER, PurchaseOrder.class)
				.setParameter("purchaseRequisition", purchaseRequisition)
				.setParameter("supplier", supplier)
				.setParameter("status", status);
		
		try {
			return query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public void delete(Long id) {
		PurchaseOrder entity = read(id);
		
		em.remove(entity);
	}
	
}
